<template>
  <view class="content">
    <view class="top-warp">
      <view class="user-tips">
        <text class="iconfont icon-shezhi02-L" @click="goRoutePage('setUp')" />
        <uni-badge
          class="uni-badge-left-margin"
          :text="systemMessageCount"
          absolute="rightTop"
          size="small"
        >
          <text
            class="iconfont icon-message"
            @click="goRoutePage('systemNew')"
          />
        </uni-badge>
      </view>
      <view class="user-myself">
        <button
            class="u-photo"
            style="border-radius: 50%"
            open-type="chooseAvatar"
            @chooseavatar="onChooseavatar"
        >
          <img
              :src="userState.avatar ? userState.avatar : baseAvatarUrl"
              alt=""
              @click="userAvatarHandleClick"
          />
        </button>

        <view class="u-userInfo">
          <view class="u-name-box">
            <text class="u-name" @click="goRoutePage('library')">{{
              userState.nickname || "Lisa"
            }}</text
            >&nbsp;
            <text class="u-position">{{ position(userState.userType) }}</text>
          </view>
          <text class="u-member">
            {{ joinCompanyState(userState.enterpriseId ? 1 : 0) }}
          </text>
          <view class="u-badge-box">
            <view class="u-badge unrecognized" v-if="!userState.hasIdCard">
              未实名
            </view>
            <view class="u-badge authenticated" v-if="userState.hasIdCard"
              >已实名</view
            >
            <view class="u-badge administrators" v-if="enterpriseManger === 1"
              >管理员</view
            >
          </view>
          <!-- <view class="sale-ratio">
            荣耀权益
            <text class="ratio">{{ honorRights }}</text>
            折
          </view> -->
        </view>
      </view>

      <view v-if="userInfoObj === null" class="to-login" @click="toLoginPage()">点击登录</view>

	  <view class="person-discount">
		  <view class="person-discount-item" v-for="payment in paymentList" :key="payment.name" @click="handleGridItemClick(payment.name, payment.route)">
			  <text class="content-value">{{payment.value}}{{payment.unit}}</text>
			  <text class="content-info">{{payment.name}}</text>
		  </view>
	  </view>
      <view class="fade-out"></view>
      <view class="user-section user-box" v-if="!userState.enterpriseId">
        <text class="user-section-tip">当前你还未加入企业</text>
        <button
          v-if="userJoinEnterpriseCheck == 0"
          class="mini-btn"
          type="warn"
          size="mini"
          style="background-color: #ff9c00; margin-left: 0; margin-right: 0"
          @click="joinNow"
        >
          立即加入
        </button>
        <button
          v-else
          class="mini-btn"
          type="warn"
          size="mini"
          style="background-color: #ff9c00; margin-left: 0; margin-right: 0"
        >
          审核中
        </button>
      </view>
      <view class="user-section user-box" v-else>
        <view class="user-section-info">
          <text class="user-section-tip">{{ userState.enterpriseName }}</text>
          <br />
          <text class="user-section-tip"
            >管理员:{{ userState.enterpriseMangerName }}</text
          >
        </view>
        <!-- <button
          class="mini-btn manager-btn"
          type="warn"
          size="mini"
          style="background-color: #ff9c00; margin-left: 0; margin-right: 0"
          @click="AdministrationClick"
        >
          管理
        </button> -->
        <!-- <view v-if="managerHasMsg" class="manager-badge" /> -->
      </view>
    </view>
    <!--    <uni-grid-->
    <!--        class="user-section"-->
    <!--        :showBorder="false"-->
    <!--        :Boolean="false"-->
    <!--        :column="3"-->
    <!--    >-->
    <!--      <uni-grid-item-->
    <!--          v-for="(order, oInd) in orderList"-->
    <!--          :key="oInd"-->
    <!--          @on-click="goOrderPage(order)"-->
    <!--      >-->
    <!--        <uni-badge-->
    <!--            class="uni-badge-left-margin"-->
    <!--            :text="order.num"-->
    <!--            absolute="rightTop"-->
    <!--            size="small"-->
    <!--            :customStyle="{ 'z-index': 5 }"-->
    <!--        >-->
    <!--          <view class="u-c-box">-->
    <!--            <img-->
    <!--                class="u-c-img"-->
    <!--                :src="order.imageUrl"-->
    <!--            />-->
    <!--            <text class="u-c-title">{{ order.name }}</text>-->
    <!--          </view>-->
    <!--        </uni-badge>-->
    <!--      </uni-grid-item>-->
    <!--    </uni-grid>-->

    <uni-grid
      class="user-section"
      :showBorder="false"
      :Boolean="false"
      :column="4"
    >
      <view v-for="(assist, aInd) in assistList" :key="aInd">
        <uni-grid-item
          v-if="assist.show"
          @on-click="handleGridItemClick(assist.name, assist.route)"
        >
          <img class="u-c-img" :src="baseImgPrefix + assist.imageUrl" alt="" />
          <text class="u-c-title">{{ assist.name }}</text>
        </uni-grid-item>
      </view>
    </uni-grid>
    <uni-popup popupStyles="z-index: 1000;" ref="popup" background-color="#fff">
    </uni-popup>
    <uni-popup ref="overlay" :before-close="true" background-color="#fff">
      <view class="popup-content">
        <view class="wrapper">
          <view class="cancellation-box">
            <view class="cancellation">
              <view class="name">绑定手机号</view>
              <view class="text-box">
                该账号未绑定手机号，请进行手机号绑定
              </view>
              <view class="tail" @click="lookClick">
                <text>去绑定</text>
              </view>
            </view>
            <view class="close-btn" @click="closeClick">X</view>
          </view>
        </view>
      </view>
    </uni-popup>
    <!-- 登录弹窗 -->
<!--    <loginDialog
      @on-off="getHome"
      @on-make="headelMake"
      :indicate="userLoginDialog"
    >
    </loginDialog>-->
  </view>
</template>
<script setup>
import loginDialog from "@/components/login/index.vue";
import { ref, reactive, getCurrentInstance, nextTick } from "vue";
import {getPurseInfoApi} from "@/api/user/cashWallet.js"
import {
  getUserInfoApi,
  getUsableOrder,
  upLoadAvatarApi,
  getUserHonorRightsApi,
  getManagerMsgBadgeApi,
  checkIsExistPhoneApi,
  getUserMsgTotalApi,
} from "@/api/user";
import { getAppEnterpriseBaseInfo } from "@/api/user/index.js";
import { onShow, onHide, onTabItemTap } from "@dcloudio/uni-app";
import UniBadge from "@/uni_modules/uni-badge/components/uni-badge/uni-badge.vue";
import UniGridItem from "@/uni_modules/uni-grid/components/uni-grid-item/uni-grid-item.vue";
import UniPopup from "@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue";
import UniGrid from "@/uni_modules/uni-grid/components/uni-grid/uni-grid.vue";
import { userGetBadgeApi } from "@/api/index";
import { customNav } from "@/utils/customNav";


// 选择头像｜手机内其他图片
const onChooseavatar = (e) => {
  new Promise((resolve, reject) => {
    // 获取图片信息（临时路径）
    uni.getImageInfo({
      src: e.detail.avatarUrl,
      success: (res) => {
        // console.log("图片信息", res)
        resolve(res);
      },
      fail: (err) => {
        // console.error("获取图片信息失败了", err)
        reject(err);
      },
    });
  })
      .then((res) => {
        return Promise.resolve({
          tempFilePath: e.detail.avatarUrl,
        });
      })
      .then((res) => {
        userState.avatar = e.detail.avatarUrl;

        uni.uploadFile({
          url: "/ht-user/user/upload",
          filePath: userState.avatar,
          name: "file",
          formData: {
            type: 2,
          },
          success: (res) => {
            const { statusCode, data } = res;
            if (statusCode === 200) {
              const parseData = JSON.parse(data);
              uploadAvatar(parseData.data);
            }
          },
        });
      })
      .catch((err) => {
        // 获取失败时使用store内默认头像
        // infoForm.avatar = userStore.userInfo.avatar
      });
};

const userLoginInfo = ref("");
const userLoginDialog = ref(false);
const baseAvatarUrl =
  "https://minio.gzryzl.com/huatai/2024-03-20/1710920720001avatar.png";
const userState = reactive({
  avatar: "", //头像
  nickname: "", //昵称
  checkState: 1, //加入企业状态
  enterpriseName: "", //企业名称
  hasIdCard: false, // 是否实名认证
});
const { proxy } = getCurrentInstance();
const baseImgPrefix = "https://minio.gzryzl.com/huatai";
const paymentList=ref([])
const assistList = ref([
  // {
  //   name: "邀请加入",
  //   imageUrl: "/2024-03-26/1711445120646invite.png",
  //   route: "邀请加入",
  //   show: true,
  // },
  {
    name: "我的企业",
    imageUrl: "/2024-03-20/1710926277278tourist.png",
    route: "Joining-enterprise",
    show: true,
  },
  {
    name: "加入企业",
    imageUrl: "/2024-03-20/1710926277278tourist.png",
    route: "Joining-enterprise",
    show: true,
  },
	{
	  name: "申请管理员",
	  imageUrl: "/2024-03-20/1710926277278tourist.png",
	  route: "administratorApply",
	  show: false,
	},
  {
    name: "意见反馈",
    imageUrl: "/2024-03-20/1710926358848feedback.png",
    route: "feedback",
    show: true,
  },
  // {
  //   name: "帮助与客服",
  //   imageUrl: "/2024-03-20/1710924213508help.png",
  //   route: "/package_customer_service/pages/customer-service/index",
  //   show: true,
  // },
  /*{
    name: "实名认证",
    imageUrl: "/2024-03-20/1710924698755realName.png",
    route: "name-authentication",
    show: true,
  },*/
  // {
  //   name: "上传资料",
  //   imageUrl: "/2024-03-26/1711447581122upload.png",
  //   route: "upload-data",
  //   show: true,
  // },
  {
    name: "我的荣誉",
    imageUrl: "/2024-07-30/1722309260682my_honor.png",
    route: "my-honor",
    show: true,
  },
  {
    name: "我的徽章",
    imageUrl: "/2024-06-05/1717556322119矢量智能对象@2x.png",
    route: "myBadge",
    show: true,
  },
  {
    name: "扫一扫",
    imageUrl: "/2024-06-05/1717556833226矢量智能对象@2x (1).png",
    route: "index",
    show: true,
  },
  {
    name: "优惠规则",
    imageUrl: "/2024-06-05/1717556936785矢量智能对象@2x (2).png",
    route: "discountRules",
    show: true,
  },
  // {
  //   name: "优惠券",
  //   imageUrl: "/2024-10-11/1728628607199coupon.png",
  //   route: "/package_coupon/pages/s",
  //   show: true,
  // },
]);
const userInfoObj = ref(null);
const inviteObj = ref({});
const orderList = ref([
  {
    id: 4,
    name: "全部订单",
    imageUrl:
      "https://minio.gzryzl.com/huatai/2024-03-20/1710926541596total.png",
  },
  {
    name: "待使用",
    num: 0,
    imageUrl:
      "https://minio.gzryzl.com/huatai/2024-03-20/1710926541596total.png",
  },
  // { name: "待提货", num: 25, imageUrl: "exchange.png" },
  {
    id: 3,
    name: "已完成",
    imageUrl:
      "https://minio.gzryzl.com/huatai/2024-03-20/1710926615910completed.png",
  },
]);
const userList = ref([
  { name: "权益分", num: 25, route: "integral" },
  { name: "优惠券", num: 25, route: "coupon" },
  { name: "荣誉空间", num: 25, route: "my-honor" },
  { name: "累计揭榜", num: 25, route: "unveil" },
]);

const enterpriseId = ref();
const enterpriseName = ref();
const systemMessageCount = ref(0);
const userJoinEnterpriseCheck = ref(0); //是否存在加入企业未审核的申请0否 1是
const enterpriseManger = ref(0); //是否企业管理员 0否 1是

function getHome() {
  uni.switchTab({
    url: "/pages/index/index",
  });
}
const joinCompanyState = (state) => {
  switch (state) {
    case 0:
      return "未加入企业";
    case 1:
      return "已加入企业";
  }
};

const position = (state) => {
  switch (state) {
    case 0:
      return "";
    case 1:
      return "管理员";
    case 2:
      return "玩家";
  }
};

// 管理员账号获取审核消息提示
const managerHasMsg = ref(false);
const getManagerMsgBadgeFlag = async () => {
  const res = await getManagerMsgBadgeApi();
  const { code, data } = res;
  if (code === 200) {
    managerHasMsg.value = !!Number(data);
  }
};
function closeClick() {
  proxy.$refs.overlay.close();
}
// 获取用户详细信息
const getUserInfoFn = () => {
  getUserInfoApi().then((res) => {
    userInfoObj.value = res.data;
    if (res.data.enterpriseManger === 1) {
      assistList.value[0].show = true;
      assistList.value[1].show = true;
			assistList.value[2].show = false;
      getManagerMsgBadgeFlag();
    }
    enterpriseManger.value = res.data.enterpriseManger;
    uni.setStorageSync("enterpriseManger", res.data.enterpriseManger);
    enterpriseId.value = res.data.enterpriseId;
    userJoinEnterpriseCheck.value = res.data.userJoinEnterpriseCheck;
    uni.setStorageSync("enterpriseId", res.data.enterpriseId);
    uni.setStorageSync("avatar", res.data.avatar);
    enterpriseName.value = res.data.enterpriseName;
    if (res.code === 200) {
      Object.keys(res.data).forEach((item) => {
        const { code, data } = res;
        if (code === 200) {
          nextTick(() => {
            const { hasIdCard } = data || {};
            if (hasIdCard) {
              const findAssist = assistList.value.find(
                (assist) => assist.name === "实名认证"
              );
              findAssist.show = false;
            }
          });
          Object.keys(data).forEach((item) => {
            userState[item] = res.data[item];

            userList.value.forEach((item) => {
              switch (item.name) {
                case "权益分":
                  item.num = userState.integral;
                  break;
                case "优惠券":
                  item.num = userState.yyjNumber;
                  break;
                case "荣誉空间":
                  item.num = userState.honorNumber;
                  break;
                case "累计揭榜":
                  item.num = userState.jbNumber;
                  break;
              }
            });
          });
        }
      });
      console.log("userState", userState);
      assistList.value.map((assist) => {
        if (assist.name === "邀请加入") {
          return (assist.show = enterpriseManger.value === 1);
        }
        if (assist.name === "加入企业") {
          return (assist.show =
            enterpriseManger.value !== 1 && userState.enterpriseId == "");
        }
        if (assist.name === "我的企业") {
          return (assist.show = userState.enterpriseId);
        }
				if (assist.name === "申请管理员") {
				  return (assist.show = enterpriseId.value>0 && enterpriseManger.value<1);
				}
      });
    }
  });
  // checkIsExistPhoneApi().then((res) => {
  //     console.log("checkIsExistPhoneApi", res);
  //     if (!res.success) {
  //         proxy.$refs.overlay.open("centent");
  //     }
  //   });
};
// 获取可使用订单数量
const getUsableOrderFn = (item) => {
  getUsableOrder().then((res) => {
    if (res.code === 200) {
      item.num = res.data;
    }
  });
};

const honorRights = ref(0);
const getHonorRights = async () => {
  const res = await getUserHonorRightsApi();
  const { code, data } = res;
  if (code === 200) {
    honorRights.value = (data.discount * 10).toFixed(1);
  }
};

const getAppEnterpriseBaseInfoData = async () => {
  const res = await getAppEnterpriseBaseInfo(userInfoObj.value.enterpriseId);
  await nextTick(() => {
    inviteObj.value = res.data;
  });
};

const handleGridItemClick = (name, route) => {
  switch (name) {
    case "扫一扫":
      // #ifdef H5
      window.mobile.jsCallOpenQrScan();
      // #endif
      // #ifdef MP-WEIXIN
      uni.scanCode({
        onlyFromCamera: true,
        scanType: ["qrCode"],
        autoZoom: true,
        success: (res) => {
          console.log(res);
          if (res.result.includes("https")) {
            let code = res.result.split("=")[1];
            customNav(`/package_payment/pages/index?shops_code=${code}`);
          } else {
            let json = JSON.parse(res.result);
            console.log("扫码结果", json);
            if (json.type == "活动二维码") {
              parseQRcode();
            }
          }
        },
        fail: (err) => {
          console.error("扫码错误", err);
        },
        complete: (res) => {
          console.log("擦屁股");
        },
      });
      // #endif
      break;
    case "帮助与客服":
      customNav(route);
      break;
    case "优惠券":
      customNav(route);
      break;
	case "现金钱包":
	  customNav(route);
	  break;
	case "荣耀金豆":
	  customNav(route);
	  break;
    case "我的企业":
      AdministrationClick();
      break;
		case "申请管理员":
			applyAdministrator()
			break;
    default:
      customNav(`/package_user/pages/user/${route}`);
      break;
  }
};

function goRoutePage(name) {
  if (name === "邀请加入") {
    proxy.$refs.popup.open("bottom");
    getAppEnterpriseBaseInfoData();
    return;
  }
  if (name === "customer-service") {
    customNav("/package_customer_service/pages/customer-service/index");
  } else {
    customNav(`/package_user/pages/user/${name}`);
  }
}

const parseQRcode = () => {
  uni.vibrateShort();
};

const goOrderPage = (vm) => {
  customNav(`/package_user/pages/user/order?type=${vm.name}`);
};

function joinNow() {
  customNav("/package_user/pages/user/Joining-enterprise");
}

function AdministrationClick() {
  customNav(
    `/package_user/pages/user/administration?name=${enterpriseName.value}&enterpriseId=${enterpriseId.value}`
  );
}
function applyAdministrator() {
	customNav(
	  `/package_user/pages/user/administratorApply?enterpriseName=${enterpriseName.value}&id=${enterpriseId.value}`
	);
}
/**
 * 监听头像点击事件
 */
const userAvatarHandleClick = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ["original", "compressed"],
    sourceType: ["album", "camera"],
    success: async (res) => {
      const { tempFilePaths } = res || {};
      const tempFile = tempFilePaths[0];
      uni.uploadFile({
        url: "/ht-user/user/upload",
        filePath: tempFile,
        name: "file",
        formData: {
          type: 2,
        },
        success: (res) => {
          const { statusCode, data } = res;
          if (statusCode === 200) {
            const parseData = JSON.parse(data);
            uploadAvatar(parseData.data);
          }
        },
      });
    },
  });
};

/**
 * 上传更新头像
 * @param imgPath
 * @returns {Promise<void>}
 */
const uploadAvatar = async (imgPath) => {
  const params = {
    avatar: imgPath,
  };
  const res = await upLoadAvatarApi(params);
  const { code } = res;
  if (code === 200) {
    getUserInfoFn();
    await uni.showToast({
      title: "头像更换成功",
      icon: "success",
      duration: 2000,
    });
  }
};
const callQrCodeChange = (event) => {
  console.log("全局方法被调用QrCode:", event);
  alert("扫码结果" + window.callQrScanData);
};
function lookClick() {
  customNav("/package_login/pages/login/binding");
}
async function getUserMsgTotal() {
  const res = await getUserMsgTotalApi();
  const { code, data } = res || {};
  if (code == 200) {
    systemMessageCount.value = data;
  }
}

function headelMake() {
  userLoginDialog.value = false;
  userLoginInfo.value = uni.getStorageSync("token");
  getUserMsgTotal();
  getUserInfoFn();
  getUsableOrderFn(orderList.value[1]);
  // getSystemMsgCount();
  // getXhbMsgList();
  // getUploadDataMsgList();
  getHonorRights();
  getCashValue();
}

// 获取现金钱包
const getCashValue = ()=>{
	getPurseInfoApi().then(data=>{
		const arr = [
	{
	  name: "现金钱包",
	  route: "/package_cash_wallet/pages/index",
	  value:data.data.amount.toFixed(2)||0,
	  unit:'元'
	},
	{
	  name: "荣耀金豆",
	  route: "/package_golden_bean/pages/index",
	  value:data.data.goldenAmount||0,
	  unit:'个'
	},
	{
	  name: "优惠券",
	  route: "/package_coupon/pages/s",
	  value:data.data.couponNumber||0,
	  unit:'张'
	},
]
		paymentList.value=arr
	})
}

onTabItemTap(async (item) => {
  const { text } = item;
  if (text === "我的") {
    userLoginInfo.value = uni.getStorageSync("token");
    if (!userLoginInfo.value) {
      userLoginDialog.value = true;
    } else {
	  getCashValue();
      getUserMsgTotal();
      getUserInfoFn();
      getUsableOrderFn(orderList.value[1]);
      // getSystemMsgCount();
      // getXhbMsgList();
      // getUploadDataMsgList();
      getHonorRights();
    }
  }
});
onShow(() => {
  // #ifdef H5
  // 监听安卓扫码全局方法
  window.addEventListener("callQrScan", callQrCodeChange);
  // #endif
	getUserInfoFn();
});

onHide(() => {
  // #ifdef H5
  // 移除监听事件
  window.removeEventListener("callQrScan", callQrCodeChange);
  // #endif
});

const toLoginPage = () => {
  uni.navigateTo({ url: '/package_login/pages/login/login' })
}
</script>
<style lang="less" scoped>
@import url("../../package_user/pages/user/less/index.less");
</style>
